﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Net.Class;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Net.Properties;
using System.Threading;

namespace Net
{
    //public delegate void UpdateBalloonTip(int time, string title, string msg); //显示气泡提示的委托方法
    public partial class MainForm : Form
    {
        public static MainForm mainform;
        //private Icon mNetTrayIcon = new Icon("Tray.ico");
        private Boolean isExit = false;
       // private DateTime loginTime=null; //登录时间
        //private String returnContent;
        public MainForm()
        {
            InitializeComponent();
            mainform = this;
            //Initializenotifyicon();

        }
        private enum MyKeys
        {
            None = 0,
            Alt = 1,
            Ctrl = 2,
            Shift = 4,
            Win = 8
        }

       

        //private void Initializenotifyicon()
        //{
        //    //设定托盘程序的各个属性
        //    TrayIcon trayIcon= new NotifyIcon();
        //    trayIcon.Icon = mNetTrayIcon;
        //    trayIcon.Text = "用Visual C#做托盘程序" + " " + "作者：XXX";
        //    trayIcon.Visible = true;
        //    trayIcon.Click += new System.EventHandler(this.click);

        //}
        //void updateBalloonTip(int time,string title,string msg)
        //{
        //    this.notifyIcon1.ShowBalloonTip(time, title, msg, ToolTipIcon.Info);
        //}

        public void login(object sender, EventArgs e)
        {
            this.notifyIcon1.ShowBalloonTip(30000, "用户登录", "正在执行登录操作，请耐心等待……", ToolTipIcon.Info);
            string username = txt_userName.Text.Trim();
            string password = txt_passWord.Text.Trim();
            if ("".Equals(username) || "".Equals(password))
            {

                this.notifyIcon1.ShowBalloonTip(2000, "信息不完整 ", "用户名或密码不能为空，请检查", ToolTipIcon.Info);
                return;
            }
            String strFormData;
            String netIn;
            if (checkBox_if_login.Checked)
            {
                netIn = "Y";
            }
            else
            {
                netIn = "N";
            }
            strFormData = "username=" + txt_userName.Text.Trim() + "&password=" + txt_passWord.Text.Trim() + "&if_login=" + netIn;
            String postUrl = "http://202.202.96.53/login/login1.jsp";
            String returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, strFormData));
            richTextBox1.Text = returnContent;
            //Log.WriteLine("登录返回信息", returnContent);

            if (returnContent == null || returnContent.Equals(""))
            {
                //modify on 2011-3-9 begin
                postUrl = "http://202.202.96.57/login/login1.jsp";
                this.notifyIcon1.ShowBalloonTip(20000, "登录超时 ", "请求超时，结果未知，正在尝试用其他地址登录……", ToolTipIcon.Info);
                returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, strFormData));
                if (returnContent == null || returnContent.Equals(""))
                {
                    postUrl = "http://202.202.96.44/login/login1.jsp";
                    this.notifyIcon1.ShowBalloonTip(20000, "登录超时 ", "请求超时，结果未知，正在尝试用其他地址登录……", ToolTipIcon.Info);
                    returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, strFormData));
                    if (returnContent == null || returnContent.Equals(""))
                    {
                        balloonTipClickEnable = true;
                        timer4.Enabled = true;
                        urlType = URLTYPE_SYSTEM;
                        this.notifyIcon1.ShowBalloonTip(2000, "登录超时 ", "请求超时，结果未知，请重试或尝试Web登录。\n单击此处打开校园网登录服务站……", ToolTipIcon.Info);
                        Log.WriteLine(txt_userName.Text.Trim(), "登录超时:请求超时，结果未知，请重试或尝试Web登录。\n单击此处打开校园网登录服务站……");
                        setNotifyIcon1Status("未知");
                        label_loginStatus.Text = "未知";
                        return;
                    }
                }
            }
            string popMessage = "";
            Regex r = new Regex("您已通过登录审核");
            Match m = r.Match(returnContent);
            if (m.Success)
            {
                //setNotifyIcon1Status("已登录");
                //label_loginStatus.Text = "已登录";
                this.saveUserInfo();//save user name(password)
                //this.loginTime = DateTime.Now; //登录时间
                //if (checkBox_if_login.Checked)
                //{
                //    计费方式ToolStripMenuItem.Enabled = true;
                //    toolStripMenuItem4.Enabled = true;
                //}
                popMessage = "您已通过登录审核……";
                r = new Regex("费用不足，登录成功但不能访问校外");
                m = r.Match(returnContent);
                if (m.Success) //登录成功，但是没钱了
                {
                    popMessage += "\n费用不足，登录成功但不能访问校外";
                    //setNotifyIcon1Status("已登录，费用不足");
                    //label_loginStatus.Text = "已登录，费用不足";
                }
                r = new Regex("用户名:UserID:");
                m = r.Match(returnContent);
                if (m.Success) //登录成功，也有钱，可以访问外网
                {
                    string userName = NetCommon.getStringBetween(returnContent, "用户名:UserID:", "IP地址:IPAddress:");
                    String ipAddress = NetCommon.getStringBetween(returnContent, "IP地址:IPAddress:", "网费查询");
                    popMessage += "\n" + "用户名:" + userName;
                    popMessage += "\n" + "IP地址:" + ipAddress;
                }
                if (!Settings.Default.isIEDisabled)
                {
                    string url = checkBox_if_login.Checked ? Settings.Default.firstURL : Settings.Default.firstUrlIn;
                    popMessage += "\n" + "单击这里打开" + url;
                    balloonTipClickEnable = true;
                    timer4.Enabled = true;
                    urlType = URLTYPE_USER;
                    if (Settings.Default.isAutoIE)
                    {
                        // System.Diagnostics.Process.Start(url);
                        openUrl(url);
                    }

                }

                if (定时退出帐户ToolStripMenuItem.Checked) //启动定时任务
                {
                    popMessage += "\n已启动定时任务，您的帐户将会在";
                    if (Settings.Default.isAutoQuitBytime)
                    {
                        timer1.Interval = 1000 * 60 * Convert.ToInt32(Settings.Default.autoQuitTime);
                        //timer1.Interval = 1000 * 60 * 9999; //test max
                        timer1.Enabled = true;
                        popMessage += "计时达到" + Settings.Default.autoQuitTime + "分钟";
                    }
                    if (Settings.Default.isAutoQuitByflow && checkBox_if_login.Checked)//登陆外网的时候才有流量产生，方可启动流量监控
                    {
                        timer2.Enabled = true;
                        if (Settings.Default.isAutoQuitBytime) popMessage += "或";
                        popMessage += "流量达到" + Settings.Default.autoQuitFlow + "M ";
                    }
                    if (Settings.Default.isAutoQuitByMoney && checkBox_if_login.Checked)//登陆外网的时候才有费用产生，方可启动费用监控
                    {
                        if (Settings.Default.isAutoQuitBytime || Settings.Default.isAutoQuitByflow) popMessage += "或";
                        timer_money.Enabled = true;
                        popMessage += "费用达到" + Settings.Default.autoQuitMoney + "元";
                    }
                    popMessage += "后自动退出\n当前系统时间是：" + DateTime.Now.ToString();// +"\n为了保证退出帐户，请不要勾选自动重登";
                    if (Settings.Default.isAutoQuitBytime && !Settings.Default.isAutoQuitByflow && !Settings.Default.isAutoQuitByMoney)
                    {
                        DateTime timeToQuit = DateTime.Now.AddMinutes(Convert.ToInt32(Settings.Default.autoQuitTime));
                        popMessage += "\n预期退出时间是：" + timeToQuit.ToString();
                    }
                    //setNotifyIcon1Status("已登录，定时已启动");
                    //label_loginStatus.Text = "已登录，定时已启动";
                }
                this.notifyIcon1.ShowBalloonTip(1000, "登录成功 ", popMessage, ToolTipIcon.Info);
                Log.WriteLine(txt_userName.Text.Trim(), popMessage);
                isLogin();//显示登录状态
                return;
            }
            r = new Regex("本机已经登录");
            m = r.Match(returnContent);
            if (m.Success)
            {
                if (checkBox_forceLogin.Checked)
                {
                    this.logoutAndLogin(sender, e);
                }
                else
                {
                    //setNotifyIcon1Status("已登录");
                    //label_loginStatus.Text = "已登录";
                    this.notifyIcon1.ShowBalloonTip(2000, "登录失败 ", "本机已经登录……\n请先退出登录", ToolTipIcon.Info);
                    Log.WriteLine(txt_userName.Text.Trim(), "本机已经登录……\n请先退出登录");
                }
                return;
            }
            r = new Regex("账号已在其他计算机上登录");
            m = r.Match(returnContent);
            if (m.Success)
            {
                if (checkBox_forceLogin.Checked)
                {
                    toolStripMenuItem2_Click(sender, e);//从其他地方退出
                    this.logoutAndLogin(sender, e);//退出本地帐户，然后登录当前用户
                }
                else
                {

                    this.notifyIcon1.ShowBalloonTip(2000, "登录失败 ", "账号已在其他计算机上登录，请先退出该账号", ToolTipIcon.Info);
                    Log.WriteLine(txt_userName.Text.Trim(), "账号已在其他计算机上登录，请先退出该账号");
                }
                this.saveUserInfo();//save user name(password)
                return;
            }
            r = new Regex("密码错误");
            m = r.Match(returnContent);
            if (m.Success)
            {
                this.notifyIcon1.ShowBalloonTip(2000, "登录失败 ", "无法通过登录审核\n密码错误……\n请确认用户名和密码是否正确", ToolTipIcon.Info);
                Log.WriteLine(txt_userName.Text.Trim(), "无法通过登录审核\n密码错误……\n请确认用户名和密码是否正确");
                setNotifyIcon1Status("未登录");
                label_loginStatus.Text = "未登录";
                return;
            }
            r = new Regex("本机不是校内IP");
            m = r.Match(returnContent);
            if (m.Success)
            {
                this.notifyIcon1.ShowBalloonTip(2000, "登录失败 ", "无法通过登录审核\n本机不是校内IP……", ToolTipIcon.Info);
                Log.WriteLine(txt_userName.Text.Trim(), "无法通过登录审核\n本机不是校内IP……");
                setNotifyIcon1Status("未登录");
                label_loginStatus.Text = "未登录";
                return;
            }
        }

        public void button_login_Click(object sender, EventArgs e)
        {
            
            //strFormData = "username=" + txt_userName.Text.Trim() + "&password=" + txt_passWord.Text.Trim() + "&if_login=" + netIn;
            Login login = new Login();
            //login.strFormData = strFormData;
            login.mainform = this;
            login.sender = sender;
            login.e = e;
            //login.ur = new UpdateBalloonTip(updateBalloonTip);
            Thread loginThread = new Thread(new ThreadStart(login.login));
            loginThread.Start();
            //保存用户名（密码）
            //if (this.checkBox_saveUser.Checked)
            //{
            //    NetConfig.AppSettingsSave(txt_userName.Text.Trim(), txt_passWord.Text.Trim());
            //}
            //else
            //{
            //    NetConfig.AppSettingsSave(txt_userName.Text.Trim(), "");
            //}
            
        }
        private const int URLTYPE_USER = 0;
        private const int URLTYPE_SYSTEM = 1;
        public int urlType = URLTYPE_USER;
        public void logout(object sender, EventArgs e)
        {
            balloonTipClickEnable = false;
            this.notifyIcon1.ShowBalloonTip(5000, "退出帐户提醒： ", "正在退出帐户……请耐心等待", ToolTipIcon.Info);
            String postUrl = "http://202.202.96.53/login/logout1.jsp";
            String returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, ""));
            richTextBox1.Text =  returnContent;

            if (returnContent == null || returnContent.Equals(""))
            {
                returnContent = NetCommon.striphtml(GetPage.getPage("http://202.202.96.44/login/logout1.jsp", ""));
                if (returnContent == null || returnContent.Equals(""))
                {
                    balloonTipClickEnable = true;
                    timer4.Enabled = true;
                    urlType = URLTYPE_SYSTEM;
                    this.notifyIcon1.ShowBalloonTip(2000, "退出帐户失败 ", "请求超时，结果未知，请重试或尝试Web方式退出。\n单击此处打开校园网登录服务站……", ToolTipIcon.Info);
                    Log.WriteLine(txt_userName.Text.Trim(), "请求超时，结果未知，请重试或尝试Web方式退出。\n单击此处打开校园网登录服务站……");
                    return;
                }
            }

            Regex r = new Regex("您的退出请求已被接受");
            Match m = r.Match(returnContent);
            if (m.Success)
            {
                setNotifyIcon1Status("未登录");
                label_loginStatus.Text = "未登录";
                //计费方式ToolStripMenuItem.Enabled = false;//退出后就不能修改计费方式了，以防有人恶作剧肆意修改别人的帐户
                //toolStripMenuItem4.Enabled = false;

                //退出成功当前定时任务就终止
                //this.定时退出帐户ToolStripMenuItem.Checked = false;
                //this.定时退出帐户ToolStripMenuItem1.Checked = false;
                this.timer1.Enabled = false;
                this.timer2.Enabled = false;
                timer_money.Enabled = false;

                r = new Regex("账户余额:");
                m = r.Match(returnContent);
                if (m.Success) //这种情况表示帐户上没钱
                {
                    string tipString = "您的退出请求已被接受……";
                    //string userName = txt_userName.Text.Trim();
                    String moneyLeftInAccount = NetCommon.getStringBetween(returnContent, "账户余额:", "登录时间:");
                    string loginTime = NetCommon.getStringBetween(returnContent, "登录时间:", "退出时间:");
                    String logoutTime = NetCommon.getStringBetween(returnContent, "退出时间:", "详单查询");
                    //tipString = tipString + "\n" + "您的帐户名：" + userName;
                    tipString = tipString + "\n" + "账户余额：" + moneyLeftInAccount;
                    tipString = tipString + "\n" + "登录时间：" + loginTime;
                    tipString = tipString + "\n" + "退出时间：" + logoutTime;
                    this.notifyIcon1.ShowBalloonTip(2000, "退出帐户成功 ", tipString, ToolTipIcon.Info);
                    Log.WriteLine(txt_userName.Text.Trim(), tipString);
                }
                else  //帐户里有钱，有消费记录产生
                {
                    string tipString = "您的退出请求已被接受……";
                    String userName = NetCommon.getStringBetween(returnContent, "用户名:", "本次花费:");
                    String moneyCostThisTime = NetCommon.getStringBetween(returnContent, "本次花费:", "登录时间:");
                    string loginTime = NetCommon.getStringBetween(returnContent, "登录时间:", "退出时间:");
                    String logoutTime = NetCommon.getStringBetween(returnContent, "退出时间:", "详单查询");
                    tipString = tipString + "\n" + "您的帐户名：" + userName;
                    tipString = tipString + "\n" + "本次花费：" + moneyCostThisTime;
                    tipString = tipString + "\n" + "登录时间：" + loginTime;
                    tipString = tipString + "\n" + "退出时间：" + logoutTime;
                    this.notifyIcon1.ShowBalloonTip(2000, "退出帐户成功 ", tipString, ToolTipIcon.Info);
                    Log.WriteLine(txt_userName.Text.Trim(), tipString);
                }
               
            }
        }
        private void button_logout_Click(object sender, EventArgs e)
        {
            Logout logout = new Logout();
            //login.strFormData = strFormData;
            logout.mainform = this;
            logout.sender = sender;
            logout.e = e;
            //login.ur = new UpdateBalloonTip(updateBalloonTip);
            Thread loginThread = new Thread(new ThreadStart(logout.logout));
            loginThread.Start();
            //if (this.checkBox_ifAutoLogin.Checked)
            //{
            //    this.button_login_Click(sender, e);
            //}
            //r = new Regex("本机已经登录");
            //m = r.Match(returnContent);
            //if (m.Success)
            //{
            //    this.notifyIcon1.ShowBalloonTip(2000, "退出帐户失败 ", "本机已经登录……\n请先退出登录", ToolTipIcon.Info);
            //}
        }

        private void 登录帐户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.button_login_Click(sender,e);
        }

        private void 退出帐户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.button_logout_Click(sender, e);
        }
        //注册热键
        [DllImportAttribute("user32.dll", EntryPoint = "RegisterHotKey")]
        public static extern bool RegisterHotKey
            (
                IntPtr hWnd,        //要注册热键的窗口句柄      
                int id,             //热键编号      
                int fsModifiers,    //特殊键如：Ctrl，Alt，Shift，Window      
                int vk              //一般键如：A B C F1，F2 等      
            );

        [DllImportAttribute("user32.dll", EntryPoint = "UnregisterHotKey")]
        public static extern bool UnregisterHotKey
            (
                IntPtr hWnd,        //注册热键的窗口句柄      
                int id              //热键编号上面注册热键的编号      
            );      



        private void MainForm_Load(object sender, EventArgs e)
        {
             Log.WriteLine(Settings.Default.username, "系统启动");
            this.checkBox_if_login.Checked = Settings.Default.isVisitOut;
            this.checkBox_saveUser.Checked = Settings.Default.isSavePassword;
            checkBox_forceLogin.Checked = Settings.Default.isForceLogin;
            checkBox_ifAutoLogin.Checked = Settings.Default.isAutoLogin;
            this.txt_userName.Text = Settings.Default.username;//just for test
            txt_passWord.Text = Encrypt.DESDecrypt(Settings.Default.password);
            //Hashtable hashtable = (Hashtable)Settings.Default.users;
            if (Settings.Default.usernames != null && Settings.Default.usernames.Count > 0)
            {

                for (int i = 0; i < Settings.Default.usernames.Count; i++)
                {
                    string name = Settings.Default.usernames[i];
                    //string passwordtemp = Encrypt.DESDecrypt(Settings.Default.passwords[i]);
                    if(name !=null && !name.Equals(""))
                    txt_userName.Items.Add(name);
                    //if (name.Equals(Settings.Default.username))
                    //{
                    //    txt_userName.Text = name;
                    //    txt_passWord.Text = passwordtemp;
                    //}
                }
            }
            //计费方式ToolStripMenuItem.Enabled = false;
            //toolStripMenuItem4.Enabled = false;
           // this.notifySys.Visible = true;
            this.notifyIcon1.Visible = true;
            //this.MaximizeBox = false;
            //this.MinimizeBox = false;
            //this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
            this.ShowInTaskbar = true;
            
            //string[] userInfo =  NetConfig.getUser();//从配置文件读取保存的用户名和密码，这样不安全
            //if (userInfo !=null&&userInfo.Length > 0)
            //{
            //    this.txt_userName.Text = userInfo[0];
            //    this.txt_passWord.Text = userInfo[1];
            //}

            //RegisterHotKey(this.Handle, 200, (int)MyKeys.Alt, (int)Keys.I); //注册热键Alt+A      
           // RegisterHotKey(this.Handle, 200,(int)MyKeys.Ctrl|(int)MyKeys.Alt, (int)Keys.I);// 注册热键Ctrl+Alt+I     
            //RegisterHotKey(this.Handle, 200, (int)MyKeys.None, (int)Keys.F2); //注册热键F2      
            //if(this.checkBox_if_login.Checked&&this.isLogin())
            //{
            //    label_loginStatus.Text = "已登录";
            //}

            button1.Enabled = checkBox_if_login.Checked ? true : false;
            费用查询ToolStripMenuItem.Enabled = checkBox_if_login.Checked ? true : false;
            toolStripMenuItem1.Enabled = checkBox_if_login.Checked ? true : false;

            if (Settings.Default.isAutoLoginStart) //程序启动后自动登录
            {
                if (!"".Equals(Settings.Default.username) && !"".Equals(Settings.Default.password))
                {
                    this.button_login_Click(sender, e);
                }
            }
            if(Settings.Default.showStatus) timer3.Enabled = true;//实时判断登录状态

            //常用网址初始化
            //ToolStripDropDownItem ts = ((ToolStripDropDownItem)contextMenuStrip1.Items["aToolStripMenuItem"]);
            //ts = ((ToolStripDropDownItem)ts.DropDownItems["toolStripMenuItem_url"]);
            //ts.DropDownItems.Add(new ToolStripMenuItem("test"));

            ToolStripMenuItem mi = (ToolStripMenuItem)contextMenuStrip1.Items["toolStripMenuItem_url"];//new ToolStripMenuItem("背景");
            //mi.DropDownItems.Add("");
            //this.contextMenuStrip1.Items.Add(mi);
           // mi.Click += new System.EventHandler(mi_Click);
            if (Settings.Default.urls != null)
            {
                for (int i = 0; i < Settings.Default.urls.Count; i++)
                {
                    if (Settings.Default.urls[i] != null && !Settings.Default.urls[i].Equals(""))
                    {
                        //ToolStripMenuItem[] ShouCangsMenuItem = new ToolStripMenuItem[1];
                        //ShouCangsMenuItem[0] = new System.Windows.Forms.ToolStripMenuItem();
                        ToolStripMenuItem ShouCangsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
                        ShouCangsMenuItem.Text = Settings.Default.titles[i] ;
                        ShouCangsMenuItem.Click += new EventHandler(mi_Click);
                        mi.DropDownItems.Add(ShouCangsMenuItem);
                    }
                }
            }


           
        }

        public void mi_Click(object sender, EventArgs e)
        {
            //... 
            for (int i = 0; i < Settings.Default.urls.Count; i++)
            {
                if (Settings.Default.titles[i] != null && Settings.Default.titles[i].Equals(sender.ToString()))
                {
                    string url = Settings.Default.urls[i];
                   this.openUrl(url);
                }
            }
            //this.notifyIcon1.ShowBalloonTip(2000, "测试成功 ", sender.ToString(), ToolTipIcon.Info);
        } 

        private void 退出程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定退出程序吗？", "退出", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                this.isExit = true;
                saveSettings();
                Application.Exit();
            }
            else
            {
                退出程序ToolStripMenuItem.Enabled = true;
            }
        }



        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
           
                if (this.WindowState == System.Windows.Forms.FormWindowState.Minimized)
                {
                    this.WindowState = System.Windows.Forms.FormWindowState.Normal;
                    this.ShowInTaskbar = true;
                }
                else
                {
                    this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
                    this.ShowInTaskbar = false;
                    //this.notifyIcon1.ShowBalloonTip(2000, "BalloonTip   Title ", "Hello   BalloonTip... ", ToolTipIcon.Info);

                }
           
           
        }
       

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && e.Clicks == 1)
            {
                if (this.WindowState == System.Windows.Forms.FormWindowState.Minimized)
                {
                    this.WindowState = System.Windows.Forms.FormWindowState.Normal;
                    this.ShowInTaskbar = true;
                }
                else
                {
                    this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
                    this.ShowInTaskbar = false;
                    this.notifyIcon1.ShowBalloonTip(2000, "BalloonTip   Title ", "Hello   BalloonTip... ", ToolTipIcon.Info);

                }
            }
            else if (e.Button == MouseButtons.Right && e.Clicks == 1)
            {

                this.notifyIcon1.ShowBalloonTip(2000, "BalloonTip   Title ", "Hello   您单击了鼠标右键... ", ToolTipIcon.Info);
            }
        }

        private void 登录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.button_login_Click( sender,  e);
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.button_logout_Click(sender, e);
        }

        private void saveSettings()
        {
            Settings.Default.isVisitOut = this.checkBox_if_login.Checked;
            Settings.Default.isSavePassword = this.checkBox_saveUser.Checked;
            Settings.Default.isAutoLogin = checkBox_ifAutoLogin.Checked;
            Settings.Default.isForceLogin = checkBox_forceLogin.Checked;
            //Settings.Default.username = Encrypt.DESEncrypt( txt_userName.Text.Trim());
            //if (this.checkBox_saveUser.Checked)
            //    Settings.Default.password = Encrypt.DESEncrypt(txt_passWord.Text.Trim());
            //else Settings.Default.password = "";
            Settings.Default.Save();
        }
        public void saveUserInfo()
        {
            string username = txt_userName.Text.Trim();
            string password = "";
            if (this.checkBox_saveUser.Checked)
                password = Encrypt.DESEncrypt(txt_passWord.Text.Trim());
            if (Settings.Default.usernames == null) //还没有保存过用户信息
            {
                Settings.Default.usernames = new System.Collections.Specialized.StringCollection();
                Settings.Default.passwords = new System.Collections.Specialized.StringCollection();
                string[] temp = { "","","","",""};
                Settings.Default.usernames.AddRange(temp);
                Settings.Default.passwords.AddRange(temp);
            }

            if (Settings.Default.usernames.Contains(username))//当前用户已经存在
            {
                int index = Settings.Default.usernames.IndexOf(username);
                Settings.Default.passwords[index] = password;
            }
            else
            {
                int j = 0;
                for (j = 0; j < Settings.Default.usernames.Count; j++)
                {
                    string temp = Settings.Default.usernames[j];
                    if (temp == null || "".Equals(temp)) break;
                }
                if (j >= 5) //五个位置 已经 装满
                {
                    for (int i = 0; i < 4; i++)
                    {
                        Settings.Default.usernames[i] = Settings.Default.usernames[i + 1]; //依次前移，新用户保存到最后一个位置
                        Settings.Default.passwords[i] = Settings.Default.passwords[i + 1];
                    }
                    j = 4;//最后一个位置 
                }
                Settings.Default.usernames[j] = username;
                Settings.Default.passwords[j] = password;
                this.txt_userName.Items.Add(username);
            }

            Settings.Default.username = txt_userName.Text.Trim();
            Settings.Default.password = password;
            Settings.Default.Save();


            //////////////////////////////////////////////////////////
            //if( Settings.Default.users == null )Settings.Default.users = new Hashtable() ;
            //if (Settings.Default.users.ContainsKey(username))
            //{
            //        Settings.Default.users[username] = password;
            //}
            //else
            //{
            //    if (Settings.Default.usernames == null) Settings.Default.usernames = new Queue();
            //    if (Settings.Default.users.Count >= 5)
            //    {
            //        string key =(string) Settings.Default.usernames.Dequeue();
            //        Settings.Default.users.Remove(key);
            //    }

            //    Settings.Default.users.Add(username, password);
            //    Settings.Default.usernames.Enqueue(username);
            //    this.txt_userName.Items.Add(username);
            //    //users[username] = "";
            //}
        }

        //protected override void OnFormClosing(FormClosingEventArgs e)  
        private void Form_Closing(object sender, FormClosingEventArgs e)
        {
            /*just for debug */
            //begin
            //string debugMsg = "Form_Closing:isExit=" + isExit;
            //notifyIcon1.ShowBalloonTip(2000, "Debug 不能关机或注销的问题 ", debugMsg, ToolTipIcon.Warning);
            //end 
            if (isExit)
            {
               // UnregisterHotKey(this.Handle, 200); //注销热键
               
                saveSettings();
                if (Settings.Default.isAutoLogoutQuit) //退出程序自动退出登录
                {
                    //Settings.Default.isAutoLogin = false;//不能自动重登了，不然退不出来
                    this.button_logout_Click(sender, e);
                }
                Log.WriteLine(Settings.Default.username, "系统退出");
                return;
            }
            //string debugString = sender.ToString();
            e.Cancel = true;
            //this.Hide();
            //this.notifyIcon1.Visible = true;
            this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
            this.ShowInTaskbar = false;
            //this.notifyIcon1.ShowBalloonTip(2000, "BalloonTip   Title ", "Hello   BalloonTip... ", ToolTipIcon.Info);

        }

        private const int WM_HOTKEY = 0x312;
        private const int WM_QUERYENDSESSION = 0x0011; //0x0011 关机
        protected override void WndProc(ref Message m)
        {
            //MessageBox.Show(Convert.ToString(m.Msg));
            //const int WM_ENDSESSION   =   0x0016; 
            //switch (m.Msg)
            //{
            //    case 0x0312:
            //        if (m.WParam.ToString().Equals("888"))
            //        {
            //            this.Visible = true;
            //            this.WindowState = FormWindowState.Normal;
            //            this.notifyIcon1.Visible = false;
            //        }
            //        break;
            //    case WM_ENDSESSION:
            //        MessageBox.Show("系统关闭 "); 
            //        break;
            //}
            //base.WndProc(ref m);

            if (m.Msg == WM_HOTKEY)
            {
                switch (m.WParam.ToInt32())
                {
                    case 200:
                        this.button_login_Click(this, EventArgs.Empty);
                        break;
                   
                }
            }
            if (m.Msg == WM_QUERYENDSESSION) //操作系统通知此程序退出，如果不退出，不能关机或注销……
            {
                isExit = true;
            }

            base.WndProc(ref m);
        }

        private void sizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == System.Windows.Forms.FormWindowState.Minimized)
            {
                this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
                this.ShowInTaskbar = false;
                //this.notifyIcon1.ShowBalloonTip(2000, "BalloonTip   Title ", "Hello   BalloonTip... ", ToolTipIcon.Info);
            }
        }

        private void setChangeMoneyItemEnableStatus()
        {
           
            if (!isLogin()||!checkBox_if_login.Checked)
            {
                计费方式ToolStripMenuItem.Enabled = false;
                toolStripMenuItem4.Enabled = false;
                //setNotifyIcon1Status("未登录");
            }
            if (isLogin() || checkBox_if_login.Checked)
            {
                计费方式ToolStripMenuItem.Enabled = true;
                toolStripMenuItem4.Enabled = true;
            }

        }
        private bool isLoginInsideOrOutside()  //通过bbs检测是否登录
        {
            bool isLogin = true;
            String postUrl1 = "http://bbs.swu.edu.cn";
            String returnContent1 = NetCommon.striphtml(GetPage.getPage(postUrl1, ""));
            richTextBox1.Text = returnContent1;
            //Log.WriteLine("BBS返回内容", returnContent1);
            if (returnContent1 == null || returnContent1.Equals(""))
            {
                //setNotifyIcon1Status("未知");
                //label_loginStatus.Text = "未知";
                isLogin = false;
                timer3.Interval = timer3.Interval * 8; //Int32.MaxValue;// timer3.Interval * 2;
                return isLogin;
            }
            //String tipString="";
            Regex r1 = new Regex("发帖请先登陆校园网");
            Match m1 = r1.Match(returnContent1);
            if (m1.Success) //没有登录
            {
                setNotifyIcon1Status("未登录");
                label_loginStatus.Text = "未登录";
                //计费方式ToolStripMenuItem.Enabled = false;
                //toolStripMenuItem4.Enabled = false;
                isLogin = false;
            }
            else
            {
                //计费方式ToolStripMenuItem.Enabled = true;
                //toolStripMenuItem4.Enabled = true;
                string detail = "";
                if (this.checkBox_if_login.Checked && Settings.Default.showStatus)
                {
                    detail = "\n已访问流量："+ (Convert.ToDouble(this.getBytesVisited())/(1024*1024)).ToString("f2")  +"M\n已产生费用："+ Convert.ToString(this.getMoneyThisTime())+"元";//
                    //this.notifyIcon1.ShowBalloonTip(2000, "Debug0： "+timer3.Interval, detail, ToolTipIcon.Info);
                }
                setNotifyIcon1Status("已登录", detail);
                label_loginStatus.Text = "已登录";
                if (定时退出帐户ToolStripMenuItem.Checked)
                {
                    setNotifyIcon1Status("已登录，定时已启用", detail);
                    label_loginStatus.Text = "已登录，定时已启用";
                }
                isLogin = true;
            }
            if (timer3.Interval > 1000 && timer3.Interval <= Int32.MaxValue)
            {
                timer3.Interval = timer3.Interval / 2;
            }
            return isLogin;
        }
        private bool isLoginOutside()
        {
            bool isLogin;
            //if (isLoginInsideOrOutside()) return true;
            //else
            //{
                //以下为检测外网登录状态……
                String postUrl = "http://202.202.96.53/account/check_now.jsp";
                String returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, ""));
                richTextBox1.Text = returnContent;
                if (returnContent == null || returnContent.Equals(""))
                {
                    //setNotifyIcon1Status("未知");
                    //label_loginStatus.Text = "未知";
                    isLogin = false;
                    timer3.Interval = timer3.Interval * 8; //Int32.MaxValue;// timer3.Interval * 2;
                    return isLogin;
                }
                Regex r = new Regex("请输入用户名和密码");
                Match m = r.Match(returnContent);
                if (m.Success)
                {
                    isLogin = false;
                    setNotifyIcon1Status("未登录");
                    label_loginStatus.Text = "未登录";
                }
                else
                {
                    isLogin = true;
                    string detail = "";
                    if (this.checkBox_if_login.Checked && Settings.Default.showStatus)
                    {
                        detail = "\n已访问流量：" + (Convert.ToDouble(this.getBytesVisited()) / (1024 * 1024)).ToString("f2") + "M\n已产生费用：" + Convert.ToString(this.getMoneyThisTime()) + "元";//
                        //this.notifyIcon1.ShowBalloonTip(2000, "Debug1： "+timer3.Interval, detail, ToolTipIcon.Info);
                    }
                    setNotifyIcon1Status("已登录", detail);
                    label_loginStatus.Text = "已登录";
                    if (定时退出帐户ToolStripMenuItem.Checked)
                    {
                        setNotifyIcon1Status("已登录，定时已启用", detail);
                        label_loginStatus.Text = "已登录，定时已启用";
                    }
                }
                if (timer3.Interval > 1000 && timer3.Interval <= Int32.MaxValue)
                {
                    timer3.Interval = timer3.Interval / 2;
                }
                return isLogin;
            //}

        }
        public bool isLogin()
        {
            if (isLoginInsideOrOutside())
            {
                return true;//肯定登录了内网或外网
            }
            else
            {
                if (this.checkBox_if_login.Checked) return isLoginOutside();
                else return false;//没有登录，或者登录了内网但是查询超时
            }
            ////if (!checkBox_if_login.Checked) //如设置为不访问校外，查询会退出帐户，因此不查询。这种情况不好处理……
            ////{
            //bool isLogin = true;
            //String postUrl1 = "http://bbs.swu.edu.cn";
            //String returnContent1 = NetCommon.striphtml(GetPage.getPage(postUrl1, ""));
            //richTextBox1.Text = returnContent1;
            //Log.WriteLine("BBS返回内容", returnContent1);
            //if (returnContent1 == null || returnContent1.Equals(""))
            //{
            //    setNotifyIcon1Status("未知");
            //    label_loginStatus.Text = "未知";
            //    isLogin = false;
               
            //}
            ////String tipString="";
            //Regex r1 = new Regex("发帖请先登陆校园网");
            //Match m1 = r1.Match(returnContent1);
            //if (m1.Success) //没有登录
            //{
            //    setNotifyIcon1Status("未登录");
            //    label_loginStatus.Text = "未登录";
            //    //计费方式ToolStripMenuItem.Enabled = false;
            //    //toolStripMenuItem4.Enabled = false;
            //    isLogin = false;
            //}
            //else
            //{
            //    //计费方式ToolStripMenuItem.Enabled = true;
            //    //toolStripMenuItem4.Enabled = true;
            //    setNotifyIcon1Status("已登录");
            //    label_loginStatus.Text = "已登录";
            //    isLogin = true;
            //}
            ////}
            //if (isLogin) return isLogin;//如果检测到已经登录，不再检测外网，要不然会退出帐户（只登录内网时）
           
        }

        private void 费用查询ToolStripMenuItem_Click(object sender, EventArgs e) //应该还不完整
        {
            if (!isLoginOutside())//可以点这个按钮，默认为一定是登在外网上的
            {
                this.notifyIcon1.ShowBalloonTip(2000, "费用查询结果： ", "您没有登录，无费用产生……", ToolTipIcon.Info);
                    return;
            }
           
            String postUrl = "http://202.202.96.53/account/check_now.jsp";
            String returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, ""));
            richTextBox1.Text = returnContent;

            if (returnContent == null || returnContent.Equals(""))
            {
                balloonTipClickEnable = true;
                timer4.Enabled = true;
                urlType = URLTYPE_SYSTEM;
                this.notifyIcon1.ShowBalloonTip(2000, "费用查询发生错误：", "请求超时，单击此处打开校园网登录服务站……", ToolTipIcon.Info);
                return;
            }
            String tipString="";
            Regex r = new Regex("请输入用户名和密码");
            Match m = r.Match(returnContent);
            if (m.Success) //没有登录
            {
                this.notifyIcon1.ShowBalloonTip(2000, "费用查询结果： ", "您没有登录，无费用产生……", ToolTipIcon.Info);
               setNotifyIcon1Status( "未登录");
               label_loginStatus.Text = "未登录";
               return;
            }
            r = new Regex("您由于费用不足因而登录后不能访问校外！所以没有费用产生");
            m = r.Match(returnContent);
            if (m.Success) //费用不足的情况
            {
                tipString = "您由于费用不足因而登录后不能访问校外……";
                String userName = returnContent.Substring(returnContent.LastIndexOf("您的用户名:") + "您的用户名:".Length, returnContent.IndexOf("您的帐上余额") - returnContent.LastIndexOf("您的用户名:") - "您的用户名:".Length).Trim();
                string moneyLeft = NetCommon.getStringBetween(returnContent, "您的帐上余额:", "您现在的漫游计费方式");
                string moneyTypeNowTemp = NetCommon.getStringBetween(returnContent, "您现在的漫游计费方式", "拨号费率");
                string moneyTypeNowName = NetCommon.getStringBetween(moneyTypeNowTemp, "计费类型:", "计费费率:");
                string moneyTypeNowContent = NetCommon.getSubStringToEnd(moneyTypeNowTemp, "计费费率:");

                string moneyTypeFutureTemp = NetCommon.getSubStringToEnd(returnContent, "您的预约漫游计费方式");
                string moneyTypeFutureName = NetCommon.getStringBetween(moneyTypeFutureTemp, "计费类型:", "计费费率:");
                string moneyTypeFutureContent = NetCommon.getStringBetween(moneyTypeFutureTemp, "计费费率:", "拨号费率");
                tipString = tipString + "\n" + "您的帐户名：" + userName;
                tipString = tipString + "\n" + "帐户余额：" + moneyLeft;
                tipString = tipString + "\n" + "您现在的漫游计费方式：" + moneyTypeNowName + "(" + moneyTypeNowContent + ")";
                tipString = tipString + "\n" + "您的预约漫游计费方式：" + moneyTypeFutureName + "(" + moneyTypeFutureContent + ")";
                this.notifyIcon1.ShowBalloonTip(2000, "费用查询结果： ", tipString, ToolTipIcon.Info);
                //setNotifyIcon1Status("已登录，费用不足");
                //label_loginStatus.Text = "已登录，费用不足";
                计费方式ToolStripMenuItem.Enabled = true;
                toolStripMenuItem4.Enabled = true;
                return;
            }
            r = new Regex("用户费用查询结果");
            m = r.Match(returnContent);
            Regex r1 = new Regex("不包括上一项");
            Match m1 = r1.Match(returnContent);
            
           // 
            if (m.Success)
            {
                if ( m1.Success)  //包月
                {
                    String userName = NetCommon.getStringBetween(returnContent, "您的用户名:", "本次上网登录时间");
                    String loginTime = NetCommon.getStringBetween(returnContent, "本次上网登录时间:", "计费类型");
                    string moneyTypeTemp = NetCommon.getStringBetween(returnContent, "本次上网登录时间:", "本次登录后已花费钱:");
                    String moneyTypeName = NetCommon.getStringBetween(moneyTypeTemp, "计费类型:", "现在计费费率");
                    String moneyTypeContent = NetCommon.getStringBetween(moneyTypeTemp, "现在计费费率:", "本次登录后已访问流量:");
                    String bytesThisTime = NetCommon.getStringBetween(returnContent, "本次登录后已访问流量:", "本次登录后已花费钱:");
                    String moneyThisTime = NetCommon.getStringBetween(returnContent, "本次登录后已花费钱:", "本次限时计费方式的余额:");
                    String moneyLeftThisType = NetCommon.getStringBetween(returnContent, "本次限时计费方式的余额:", "用户帐上余额（不包括上一项）:");
                    String moneyLeftAcount = NetCommon.getStringBetween(returnContent, "用户帐上余额（不包括上一项）:", "本次限时计费开始日期:");
                    String beginDate = NetCommon.getStringBetween(returnContent, "本次限时计费开始日期:", "本次限时计费结束日期:");
                    String endDate = NetCommon.getStringBetween(returnContent, "本次限时计费结束日期:", "您现在的漫游计费方式");
                    string moneyTypeFutureTemp = NetCommon.getSubStringToEnd(returnContent, "您的预约漫游计费方式");
                    string moneyTypeFutureName = NetCommon.getStringBetween(moneyTypeFutureTemp, "计费类型:", "计费费率:");
                    string moneyTypeFutureContent = NetCommon.getStringBetween(moneyTypeFutureTemp, "计费费率:", "拨号费率");
                    tipString = tipString + "您的帐户名：" + userName;
                    tipString = tipString + "\n" + "本次上网登录时间：" + loginTime;
                    tipString = tipString + "\n" + "您现在的计费方式：" + moneyTypeName + "(" + moneyTypeContent + ")";
                    tipString = tipString + "\n" + "本次登录后已访问流量：" + bytesThisTime;
                    tipString = tipString + "\n" + "本次登录后已花费钱：" + moneyThisTime;
                    tipString = tipString + "\n" + "本次限时计费方式的余额：" + moneyLeftThisType;
                    tipString = tipString + "\n" + "用户帐上余额（不包括上一项）：" + moneyLeftAcount;
                    tipString = tipString + "\n" + "本次限时计费开始日期：" + beginDate;
                    tipString = tipString + "\n" + "本次限时计费结束日期：" + endDate;
                    tipString = tipString + "\n" + "您的预约漫游计费方式：" + moneyTypeFutureName + "(" + moneyTypeFutureContent + ")";
                    this.notifyIcon1.ShowBalloonTip(2000, "费用查询结果： ", tipString, ToolTipIcon.Info);
                    //setNotifyIcon1Status("已登录");
                    //label_loginStatus.Text = "已登录";
                    计费方式ToolStripMenuItem.Enabled = true;
                    toolStripMenuItem4.Enabled = true;
                    return;
                }
                r1 = new Regex("不限时计费");
                m1 = r1.Match(returnContent);
                if (m1.Success) //不包月
                {
                    String userName = NetCommon.getStringBetween(returnContent, "您的用户名:", "本次上网登录时间");
                    String loginTime = NetCommon.getStringBetween(returnContent, "本次上网登录时间:", "计费类型");
                    string moneyTypeTemp = NetCommon.getStringBetween(returnContent, "本次上网登录时间:", "本次登录后已花费钱:");
                    String moneyTypeName = NetCommon.getStringBetween(moneyTypeTemp, "计费类型:", "现在计费费率");
                    String moneyTypeContent = NetCommon.getStringBetween(moneyTypeTemp, "现在计费费率:", "本次登录后已访问流量:");
                    String bytesThisTime = NetCommon.getStringBetween(returnContent, "本次登录后已访问流量:", "本次登录后已花费钱:");
                    String moneyThisTime = NetCommon.getStringBetween(returnContent, "本次登录后已花费钱:", "用户账上余额:");
                    string moneyLeft = NetCommon.getStringBetween(returnContent, "用户账上余额:", "您现在的漫游计费方式");
                    string moneyTypeFutureTemp = NetCommon.getSubStringToEnd(returnContent, "您的预约漫游计费方式");
                    string moneyTypeFutureName = NetCommon.getStringBetween(moneyTypeFutureTemp, "计费类型:", "计费费率:");
                    string moneyTypeFutureContent = NetCommon.getStringBetween(moneyTypeFutureTemp, "计费费率:", "拨号费率");
                    tipString = tipString + "您的帐户名：" + userName;
                    tipString = tipString + "\n" + "本次上网登录时间：" + loginTime;
                    tipString = tipString + "\n" + "您现在的计费方式：" + moneyTypeName + "(" + moneyTypeContent + ")";
                    tipString = tipString + "\n" + "本次登录后已访问流量：" + bytesThisTime;
                    tipString = tipString + "\n" + "本次登录后已花费钱：" + moneyThisTime;

                    tipString = tipString + "\n" + "用户帐上余额：" + NetCommon.removeBlankLines( moneyLeft.Trim());
                  
                    tipString = tipString + "\n" + "您的预约漫游计费方式：" + moneyTypeFutureName + "(" + moneyTypeFutureContent + ")";
                    this.notifyIcon1.ShowBalloonTip(2000, "费用查询结果： ", tipString, ToolTipIcon.Info);
                    //setNotifyIcon1Status("已登录");
                    //label_loginStatus.Text = "已登录";
                    计费方式ToolStripMenuItem.Enabled = true;
                    toolStripMenuItem4.Enabled = true;
                    return;
                }
            }
            this.notifyIcon1.ShowBalloonTip(2000, "费用查询结果： ", "未处理的查询结果，请联系作者处理！", ToolTipIcon.Info);
            Log.WriteLine(txt_userName.Text.Trim(), "未处理的查询结果，请联系作者处理！"+returnContent);
            //还有几种其他方式，如包月计流量，目前还不知道如何处理……
        }

        private double getMoneyThisTime()
        {
            String moneyThisTime = "";
            String postUrl = "http://202.202.96.53/account/check_now.jsp";
            String returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, ""));
            Regex r1 = new Regex("不包括上一项");
            Match m1 = r1.Match(returnContent);
            if (m1.Success)  //包月
            {
                 moneyThisTime = NetCommon.getStringBetween(returnContent, "本次登录后已花费钱:", "本次限时计费方式的余额:");
            }
            r1 = new Regex("不限时计费");
            m1 = r1.Match(returnContent);
            if (m1.Success) //不包月
            {
                moneyThisTime = NetCommon.getStringBetween(returnContent, "本次登录后已花费钱:", "用户账上余额:");
            }
            if (moneyThisTime.Equals("")) return 0;
            else
            {
                moneyThisTime = moneyThisTime.Substring(0, moneyThisTime.IndexOf("元"));
                return Convert.ToDouble(moneyThisTime);
            }
        }

        private int getBytesVisited()  //可能有的计费方式没有考虑到，缺少帐号测试
        {
            String postUrl = "http://202.202.96.53/account/check_now.jsp";
            String returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, ""));
            richTextBox1.Text = returnContent;

            if (returnContent == null || returnContent.Equals(""))
            {
                //balloonTipClickEnable = true;
                //timer4.Enabled = true;
                //urlType = URLTYPE_SYSTEM;
                //this.notifyIcon1.ShowBalloonTip(2000, "发生错误", "请求超时，单击此处打开校园网登录服务站……", ToolTipIcon.Info);
                return 0;
            }
            Regex r = new Regex("请输入用户名和密码");
            Match m = r.Match(returnContent);
            if (m.Success) //没有登录
            {
               return 0;
            }
            r = new Regex("您由于费用不足因而登录后不能访问校外！所以没有费用产生");
            m = r.Match(returnContent);
            if (m.Success) //费用不足的情况
            {
                return 0;
            }
            r = new Regex("用户费用查询结果");
            m = r.Match(returnContent);
            if (m.Success) //有流量产生
            {
                int bytes = 0;
                String bytesThisTime = NetCommon.getStringBetween(returnContent, "本次登录后已访问流量:", "本次登录后已花费钱:");
                try
                {
                     r = new Regex("M字节");
                     m = r.Match(bytesThisTime);
                     if (m.Success) //流量已超过1M
                     {
                         bytesThisTime = bytesThisTime.Replace("M字节", "");
                         bytesThisTime = bytesThisTime.Replace("M", "");
                         bytes =Convert.ToInt32(Convert.ToDouble(bytesThisTime) * 1024 * 1024);
                         bytesThisTime += "流量已超过1M";
                     }
                     else  //流量不到1M，直接返回字节的
                     {
                         bytesThisTime = bytesThisTime.Replace("M", "");
                         bytesThisTime = bytesThisTime.Replace("字节", "");
                         bytes = Convert.ToInt32(bytesThisTime);
                         bytesThisTime += "流量不到1M，直接返回字节的";
                     }
                }
                catch (Exception ex)
                {
                    this.notifyIcon1.ShowBalloonTip(2000, "发生异常 ", "bytesThisTime=" + bytesThisTime+"\n"+ex.ToString(), ToolTipIcon.Error);
                    Log.WriteLine(txt_userName.Text.Trim(), "发生异常 "+"bytesThisTime=" + bytesThisTime + "\n" + ex.ToString());
                }
                return bytes;
            }
            return 0;
        }

        private void 退出程序ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.isExit = true;
            Application.Exit();
        }

        //private void checkBox_saveUser_CheckedChanged(object sender, EventArgs e)
        //{
        //    if (this.checkBox_saveUser.Checked)
        //    {
        //        NetConfig.AppSettingsSave(txt_userName.Text.Trim(), txt_passWord.Text.Trim());
        //    }
        //    else
        //    {
        //        NetConfig.AppSettingsSave(txt_userName.Text.Trim(), "");
        //    }
        //}

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.费用查询ToolStripMenuItem_Click(sender, e);
        }

        //private void 元MToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    this.richTextBox1.Text=chooseJffs(51);
        //}
        private string getLoginUser()
        {
            if (!isLogin()) //当前IP没有用户登录，返回空
            {
                return "";
            }
            string loginUser = "";
            String postUrl = "http://202.202.96.53/account/check_now.jsp";
            String returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, ""));
            richTextBox1.Text = returnContent;
            if (returnContent == null || returnContent.Equals(""))
            {
                return "";
               
            }
            Regex r = new Regex("您由于费用不足因而登录后不能访问校外！所以没有费用产生");
            Match m = r.Match(returnContent);
            if (m.Success) //费用不足的情况
            {
                loginUser = NetCommon.getStringBetween(returnContent, "您的用户名:", "您的帐上余额");
            }

            r = new Regex("用户费用查询结果");
            m = r.Match(returnContent);
            //Regex r1 = new Regex("不包括上一项");
            //Match m1 = r1.Match(returnContent);
            if (m.Success)  //包月
            {
                loginUser = NetCommon.getStringBetween(returnContent, "您的用户名:", "本次上网登录时间"); 
            }
            return loginUser;
        }

       

        private string chooseJffs(int jffs_id)
        {
            //if (!checkBox_if_login.Checked)
            //{
            //    this.notifyIcon1.ShowBalloonTip(2000, "修改计费方式结果：", "您现在没有登录外网，为了您和他人的帐户安全，请登录外网后再执行此操作", ToolTipIcon.Info);
            //    //setChangeMoneyItemEnableStatus();//计费方式修改成功后，可能会自动退出帐户，还不确定规律
            //    return "";
            //}
            if (!isLogin())
            {
                this.notifyIcon1.ShowBalloonTip(2000, "修改计费方式结果：", "您现在没有登录，为了您和他人的帐户安全，请登录后再执行此操作", ToolTipIcon.Info);
                //setChangeMoneyItemEnableStatus();//计费方式修改成功后，可能会自动退出帐户，还不确定规律
                return "";
            }
            string userName = this.txt_userName.Text.Trim();
            if(!NetCommon.isInputValid(userName,0))
            {
                this.notifyIcon1.ShowBalloonTip(2000, "信息不完整：", "用户名输入不合法，请重新输入", ToolTipIcon.Info);
                //setChangeMoneyItemEnableStatus();//计费方式修改成功后，可能会自动退出帐户，还不确定规律
                return "";
            }
            if(!userName.Equals(getLoginUser()))
            {
                string tips = "您不能修改用户"+userName+"的计费方式，请用此用户登录外网后再进行此操作";
                this.notifyIcon1.ShowBalloonTip(2000, "非法操作：", tips, ToolTipIcon.Info);
                //setChangeMoneyItemEnableStatus();//计费方式修改成功后，可能会自动退出帐户，还不确定规律
                return "";
            }
            string formString = "username=" + userName + "&code1=1011&jffs_id=" + jffs_id;
            string postUrl = "http://202.202.96.9/account/xuanze1.jsp";
            string returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, formString));
            popInfoAfterchooseJffs(returnContent,jffs_id);
            return returnContent;
        }
        private void popInfoAfterchooseJffs(String returnContent, int jffs_id)
        {
            string tipString = "";
            if (returnContent == null || "".Equals(returnContent))
            {
                tipString = "服务器无响应……";
                this.notifyIcon1.ShowBalloonTip(2000, "计费方式修改失败 ", tipString, ToolTipIcon.Info);
            }
            Regex r = new Regex("计费方式修改成功");
            Match m = r.Match(returnContent);
            if (m.Success)
            {
                string jffsName = "修改后的计费方式：";
                switch (jffs_id)
                {
                    case 51:
                        jffsName += "宽带计量(0.05 元/M)";
                        break;
                    case 52:
                        jffsName += "包月计量(0.03 元/M)";
                        break;
                    case 54:
                        jffsName += "宽带计时(0.4 元/小时)";
                        break;
                    case 55:
                        jffsName += "包月计时(0.25 元/小时)";
                        break;
                    case 57:
                        jffsName += "定量包月(0.015 元/M)";
                        break;
                }

                tipString = "计费方式修改成功！下次登录时生效！" + "\n用户名：" + this.txt_userName.Text.Trim();
                tipString += "\n" + jffsName;
                this.notifyIcon1.ShowBalloonTip(2000, "修改计费方式结果：", tipString, ToolTipIcon.Info);
                Log.WriteLine(txt_userName.Text.Trim(), tipString);
                //setChangeMoneyItemEnableStatus();//计费方式修改成功后，可能会自动退出帐户，还不确定规律
            }
            else
            {
                tipString = NetCommon.getStringBetween(returnContent, "NewPage3", "返回");
                tipString = "".Equals(tipString) ? "有异常情况出现，请联系作者或重试" : tipString;
                this.notifyIcon1.ShowBalloonTip(2000, "修改计费方式结果：", tipString, ToolTipIcon.Info);
                Log.WriteLine(txt_userName.Text.Trim(), tipString);
            }
        }

        //private void 包月计量003元MToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    this.richTextBox1.Text = chooseJffs(54);
        //}

        private void 包月计量003元MToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确定选择这种计费方式吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                this.richTextBox1.Text = chooseJffs(52);
                if (this.checkBox_ifAutoLogin.Checked) this.logoutAndLogin(sender, e);
            }
        }

        private void 包月计时025元小时ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确定选择这种计费方式吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                this.richTextBox1.Text = chooseJffs(55);
                if (this.checkBox_ifAutoLogin.Checked) this.logoutAndLogin(sender, e);
            }
        }

        private void 定量包月0015元MToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确定选择这种计费方式吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                this.richTextBox1.Text = chooseJffs(57);
                if (this.checkBox_ifAutoLogin.Checked) this.logoutAndLogin(sender, e);
            }
        }

        private void 宽带计时04元小时MToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.richTextBox1.Text = chooseJffs(54);
            if (this.checkBox_ifAutoLogin.Checked) this.logoutAndLogin(sender, e);
        }

        private void 宽带计量005ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.richTextBox1.Text = chooseJffs(51);
            if (this.checkBox_ifAutoLogin.Checked) this.logoutAndLogin(sender, e);
        }

        private void 帐户充值ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NetCommon.userName = txt_userName.Text.Trim();
            NetCommon.passWord = txt_passWord.Text.Trim();
            FormAddMoney formAddMoney = new FormAddMoney();
            formAddMoney.StartPosition = FormStartPosition.CenterParent;
            formAddMoney.ShowDialog();
        }

        public void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            string username = txt_userName.Text.Trim();
            string password = txt_passWord.Text.Trim();
            if ("".Equals(username) || "".Equals(password))
            {
                this.notifyIcon1.ShowBalloonTip(2000, "信息不完整 ", "用户名或密码不能为空，请检查", ToolTipIcon.Info);
                return;
            }
            string postUrl = "http://service.swu.edu.cn/ipaddr/remote_logout2.jsp";
            string postData = "username=" + username + "&password=" + password ;
            string returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, postData));
            if (returnContent == null || returnContent.Equals(""))
            {
                balloonTipClickEnable = true;
                timer4.Enabled = true;
                urlType = URLTYPE_SYSTEM;
                this.notifyIcon1.ShowBalloonTip(2000, "退出帐户失败 ", "请求超时，结果未知，请重试或尝试Web方式退出。\n单击此处打开校园网登录服务站……", ToolTipIcon.Info);
                Log.WriteLine(txt_userName.Text.Trim(), "请求超时，结果未知，请重试或尝试Web方式退出。\n单击此处打开校园网登录服务站……");
                return;
            }
            this.richTextBox1.Text = returnContent;
            //Regex r = new Regex("现在没有登录");
            //Match m = r.Match(returnContent);
            //if (!m.Success)
            //{
            //    this.Close();
            //}
            string tipString = NetCommon.getSubStringToEnd(returnContent, "onmousedown=click");
            MainForm.mainform.notifyIcon1.ShowBalloonTip(2000, "强退结果：", tipString, ToolTipIcon.Info);
            Log.WriteLine(txt_userName.Text.Trim(), tipString);
            isLogin();//重新设置登录状态
            //setChangeMoneyItemEnableStatus();

        }

        private void iP地址查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string username = txt_userName.Text.Trim();
            string password = txt_passWord.Text.Trim();
            if ("".Equals(username) || "".Equals(password))
            {
                this.notifyIcon1.ShowBalloonTip(2000, "信息不完整 ", "用户名或密码不能为空，请检查", ToolTipIcon.Info);
                return;
            }
            string postUrl = "http://202.202.96.27/getip/ipview.jsp";
            string postData = "username=" + username + "&password=" + password;
            string returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, postData));
            if (returnContent == null || returnContent.Equals(""))
            {
                MainForm.mainform.notifyIcon1.ShowBalloonTip(2000, "IP查询失败 ", "请检查用户名或密码，也可能网络连接不上……", ToolTipIcon.Info);
                return;
            }
            this.richTextBox1.Text = returnContent;
            string tipString = NetCommon.getStringBetween(returnContent, "IP地址查看", "返回");
            String[] tips=tipString.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            tipString="";
            foreach (String s in tips)
            {
                if(s.Trim().Length> 0)
                {
                    tipString += s;
                    //tipString += "\r\n ";
                } 

            }
            MainForm.mainform.notifyIcon1.ShowBalloonTip(2000, "IP查询结果： ", tipString, ToolTipIcon.Info);
            Log.WriteLine(txt_userName.Text.Trim(), tipString);     
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            this.帐户充值ToolStripMenuItem_Click(sender, e);
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            this.toolStripMenuItem2_Click(sender, e);
        }

        private void 宽带计量005元MToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.宽带计量005ToolStripMenuItem_Click(sender, e);
        }

        private void 宽带计时04元小时ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.宽带计时04元小时MToolStripMenuItem_Click(sender, e);
        }

        private void 包月计量003元MToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.包月计量003元MToolStripMenuItem1_Click(sender, e);
        }

        private void 包月计时025元小时ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.包月计时025元小时ToolStripMenuItem_Click(sender, e);
        }

        private void 定量包月0015元MToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.定量包月0015元MToolStripMenuItem_Click(sender, e);
        }

        public void logoutAndLogin(object sender, EventArgs e)
        {
           
            {
                this.button_logout_Click(sender, e);
                this.button_login_Click(sender, e);
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            this.费用查询ToolStripMenuItem_Click(sender, e);
        }

        public void setNotifyIcon1Status(string status)
        {
            notifyIcon1.Text ="当前状态："+ status;
        }
        public void setNotifyIcon1Status(string status,string detail)
        {
            notifyIcon1.Text = "当前状态：" + status +detail;
        }



        private void 帐户充值ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            NetCommon.userName = txt_userName.Text.Trim();
            NetCommon.passWord = txt_passWord.Text.Trim();
            FormAddMoney formAddMoney = new FormAddMoney();
            formAddMoney.StartPosition = FormStartPosition.CenterParent;
            formAddMoney.ShowDialog();
        }

        private void 修改帐户密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NetCommon.userName = txt_userName.Text.Trim();
            NetCommon.passWord = txt_passWord.Text.Trim();
            FormPassword formPassword = new FormPassword();
            formPassword.StartPosition = FormStartPosition.CenterParent;
            formPassword.ShowDialog();
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            if (this.WindowState == System.Windows.Forms.FormWindowState.Minimized)
            {
                this.WindowState = System.Windows.Forms.FormWindowState.Normal;
                this.ShowInTaskbar = true;
            }
            else
            {
                this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
                this.ShowInTaskbar = false;
                //this.notifyIcon1.ShowBalloonTip(2000, "BalloonTip   Title ", "Hello   BalloonTip... ", ToolTipIcon.Info);

            }
        }

        private void 帐户充值ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            NetCommon.userName = txt_userName.Text.Trim();
            NetCommon.passWord = txt_passWord.Text.Trim();
            FormAddMoney formAddMoney =  FormAddMoney.childform;
            if (formAddMoney == null)
            {
                formAddMoney = FormAddMoney.signleton();
                formAddMoney.StartPosition = FormStartPosition.CenterScreen;
                formAddMoney.ShowDialog();
            }
            else
            {
                formAddMoney.Activate();
                formAddMoney.WindowState = System.Windows.Forms.FormWindowState.Normal;
            }
        }

        private void 修改帐户密码ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //FormPassword FrmCustomer = new FormPassword();
            //bool isOpened = false;
            //foreach (Form frmOpen in this.MdiChildren)
            //{
            //    if (frmOpen.Name == FrmCustomer.Name)
            //    {
            //        frmOpen.Activate();
            //        isOpened = true;
            //        break;
            //    }
            //}
            //if (isOpened == false)
            {
                NetCommon.userName = txt_userName.Text.Trim();
                NetCommon.passWord = txt_passWord.Text.Trim();
                FormPassword formPassword = FormPassword.childform;
                if (formPassword == null)
                {
                    formPassword = FormPassword.FormPasswordSignleton();
                    formPassword.StartPosition = FormStartPosition.CenterScreen;
                    formPassword.ShowDialog();
                }
                else
                {
                    formPassword.Activate();
                    formPassword.WindowState = System.Windows.Forms.FormWindowState.Normal;
                }
            }
        }
        public bool balloonTipClickEnable = false;
        private void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
        {
            if (balloonTipClickEnable)
            {

                if (urlType == URLTYPE_SYSTEM) //打开登录站
                {
                    openUrl("http://login.swu.edu.cn/index.jsp");//System.Diagnostics.Process.Start("http://login.swu.edu.cn/index.jsp");
                    //balloonTipClickEnable = false;
                }
                else if (urlType == URLTYPE_USER)
                {
                    string url = checkBox_if_login.Checked ? Settings.Default.firstURL : Settings.Default.firstUrlIn;
                    openUrl(url);//System.Diagnostics.Process.Start(url);
                    //balloonTipClickEnable = false;
                }
            }
            balloonTipClickEnable = false;
            //if (balloonTipClickEnable&&!Settings.Default.isIEDisabled)
            //{
            //    System.Diagnostics.Process.Start(Settings.Default.firstURL);
            //    balloonTipClickEnable = false;
            //}
        }

        public bool openUrl(string url)
        {
            try
            {
                System.Diagnostics.Process.Start(url);
            }
            catch (Exception ex)
            {
                notifyIcon1.ShowBalloonTip(2000,"出现异常", ex.ToString(), ToolTipIcon.Error);
                Log.WriteLine("出现异常", ex.ToString());
                return false;
            }
            return true;
        }

        private void 关于AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormAbout form = new FormAbout();
            form.StartPosition = FormStartPosition.CenterScreen;
            form.ShowDialog();
        }

        private void 程序设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormConfig form = new FormConfig();
            form.StartPosition = FormStartPosition.CenterScreen;
            form.ShowDialog();
        }

        private void 定时退出帐户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!Settings.Default.isAutoQuitBytime && !Settings.Default.isAutoQuitByflow && !Settings.Default.isAutoQuitByMoney)
            {
                notifyIcon1.ShowBalloonTip(2000, "定时退出设置失败", "定时退出功能没有打开，请在程序设置中打开这项功能", ToolTipIcon.Info);
                return;
            }
            
            this.定时退出帐户ToolStripMenuItem.Checked = !this.定时退出帐户ToolStripMenuItem.Checked;
            定时退出帐户ToolStripMenuItem1.Checked = this.定时退出帐户ToolStripMenuItem.Checked;
           
            if (定时退出帐户ToolStripMenuItem.Checked)
            {
                if (!isLogin())
                {
                    notifyIcon1.ShowBalloonTip(2000, "定时退出设置成功", "您还没有登录，登录后会启动定时任务……", ToolTipIcon.Info);
                    return;
                }
                string popMessage = "您的帐户将会在"; 
                if (Settings.Default.isAutoQuitBytime)
                {
                    timer1.Interval = 1000 * 60 * Convert.ToInt32(Settings.Default.autoQuitTime);
                    //timer1.Interval = 1000 * 60 * 9999; //test max
                    timer1.Enabled = true;
                    popMessage += "计时达到"+Settings.Default.autoQuitTime + "分钟";
                    //notifyIcon1.ShowBalloonTip(2000, "定时退出设置成功", "您的帐户将会在" + Settings.Default.autoQuitTime + "分钟后自动退出\n当前系统时间是：" + DateTime.Now.ToString() + "\n为了保证退出帐户，请不要勾选自动重登", ToolTipIcon.Info);
                }
                if (Settings.Default.isAutoQuitByflow && checkBox_if_login.Checked)
                {
                    if (Settings.Default.isAutoQuitBytime) popMessage += "或";
                    timer2.Enabled = true;
                    popMessage += "流量达到" + Settings.Default.autoQuitFlow + "M ";
                }
                if (Settings.Default.isAutoQuitByMoney && checkBox_if_login.Checked)
                {
                    if (Settings.Default.isAutoQuitBytime || Settings.Default.isAutoQuitByflow) popMessage += "或";
                    timer_money.Enabled = true;
                    popMessage += "费用达到" + Settings.Default.autoQuitMoney + "元";
                }
                popMessage += "后自动退出\n当前系统时间是：" + DateTime.Now.ToString();// +"\n为了保证退出帐户，请不要勾选自动重登"; ;
                if (Settings.Default.isAutoQuitBytime && !Settings.Default.isAutoQuitByflow && !Settings.Default.isAutoQuitByMoney)
                {
                    DateTime timeToQuit = DateTime.Now.AddMinutes(Convert.ToInt32(Settings.Default.autoQuitTime));
                    popMessage += "\n预期退出时间是：" + timeToQuit.ToString();
                }
                notifyIcon1.ShowBalloonTip(2000, "定时退出设置成功", popMessage, ToolTipIcon.Info);
                //setNotifyIcon1Status("已登录，定时已启动");
                //label_loginStatus.Text = "已登录，定时已启动";
                Log.WriteLine(txt_userName.Text.Trim(), popMessage);
             }
            else
            {
                notifyIcon1.ShowBalloonTip(2000, "定时退出设置已取消", "您的帐户不会自动退出\n为了节约费用，请不要忘记退出你的帐户", ToolTipIcon.Info);
                Log.WriteLine(txt_userName.Text.Trim(), "定时退出设置已取消:"+" 您的帐户不会自动退出\n为了节约费用，请不要忘记退出你的帐户");
                timer1.Enabled = false;
                timer2.Enabled = false;
                timer_money.Enabled = false;
                isLogin();//重新给当前状态设值
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //System.DateTime now = new DateTime();
            //notifyIcon1.ShowBalloonTip(1000, "timer1_Tick", DateTime.Now.ToString(), ToolTipIcon.Info);
            button_logout_Click(sender, e);
            timer1.Enabled = false;
            timer2.Enabled = false;
            timer_money.Enabled = false;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            int bytesVisited = getBytesVisited();
            if (bytesVisited >= (Convert.ToInt32(Settings.Default.autoQuitFlow) * 1024 * 1024))
            {
                button_logout_Click(sender, e);
                timer1.Enabled = false;
                timer2.Enabled = false;
                timer_money.Enabled = false;
            }
            
        }

        private void 定时退出帐户ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            定时退出帐户ToolStripMenuItem_Click( sender,  e);
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            FormConfig form = FormConfig.childform;
            if (form == null)
            {
                form = FormConfig.signleton();
                form.StartPosition = FormStartPosition.CenterScreen;
                form.ShowDialog();
            }
            else
            {
                form.Activate();
                form.WindowState = System.Windows.Forms.FormWindowState.Normal;
            }
        }

        private void checkBox_if_login_CheckedChanged(object sender, EventArgs e)
        {
            button1.Enabled = checkBox_if_login.Checked ? true : false;
            费用查询ToolStripMenuItem.Enabled = checkBox_if_login.Checked ? true : false;
            toolStripMenuItem1.Enabled = checkBox_if_login.Checked ? true : false;
            timer3.Enabled = checkBox_if_login.Checked ? true : false;
        }

        private void timer3_Tick(object sender, EventArgs e)
        {

            isLogin();
        }

        private void timer4_Tick(object sender, EventArgs e)
        {
            balloonTipClickEnable = false;
            timer4.Enabled = false;
        }

        private void timer_money_Tick(object sender, EventArgs e)
        {
            double moneyNow = getMoneyThisTime();
            if (moneyNow >= Convert.ToDouble(Settings.Default.autoQuitMoney))
            {
                button_logout_Click(sender, e);
                timer1.Enabled = false;
                timer2.Enabled = false;
                timer_money.Enabled = false;
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string password = "";
            if (Settings.Default.usernames != null && Settings.Default.usernames.Count > 0)
            {

                for (int i = 0; i < Settings.Default.usernames.Count; i++)
                {
                    string name = Settings.Default.usernames[i];
                    string passwordtemp = Encrypt.DESDecrypt(Settings.Default.passwords[i]);

                    if (name.Equals(txt_userName.Text.Trim()))
                    {
                        txt_userName.Text = name;
                        password = passwordtemp;
                        break;
                    }
                }
            }
            txt_passWord.Text = password;
        }

    }
    public class Logout
    {
        public MainForm mainform;
        public object sender;
        public EventArgs e;
        public void logout()
        {
            mainform.logout(sender, e);
        }
    }
    public class Login
    {
        //private const int URLTYPE_USER = 0;
        //private const int URLTYPE_SYSTEM = 1;
        //public UpdateBalloonTip ur;
        //public string posturl;
        public string strFormData;
        public MainForm mainform;
        public object sender;
        public EventArgs e;
        public void login()
        {
            mainform.login(sender,e);
        }
        //public void login()
        //{
            
        //    String postUrl = "http://202.202.96.57/login/login1.jsp";
        //    String returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, strFormData));
        //    //richTextBox1.Text = returnContent;
        //    //Log.WriteLine("登录返回信息", returnContent);

        //    if (returnContent == null || returnContent.Equals(""))
        //    {
        //        //modify on 2011-3-9 begin
        //        postUrl = "http://202.202.96.53/login/login1.jsp";
        //        this.ur(2000, "登录超时 ", "请求超时，结果未知，正在尝试用其他地址登录……");
        //        returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, strFormData));
        //        if (returnContent == null || returnContent.Equals(""))
        //        {
        //            postUrl = "http://202.202.96.44/login/login1.jsp";
        //            ur(2000, "登录超时 ", "请求超时，结果未知，正在尝试用其他地址登录……");
        //            returnContent = NetCommon.striphtml(GetPage.getPage(postUrl, strFormData));
        //            if (returnContent == null || returnContent.Equals(""))
        //            {
        //                mainform.balloonTipClickEnable = true;
        //                mainform.timer4.Enabled = true;
        //                mainform.urlType = URLTYPE_SYSTEM;
        //                mainform.notifyIcon1.ShowBalloonTip(2000, "登录超时 ", "请求超时，结果未知，请重试或尝试Web登录。\n单击此处打开校园网登录服务站……", ToolTipIcon.Info);
        //                Log.WriteLine(mainform.txt_userName.Text.Trim(), "登录超时:请求超时，结果未知，请重试或尝试Web登录。\n单击此处打开校园网登录服务站……");
        //                mainform.setNotifyIcon1Status("未知");
        //                mainform.label_loginStatus.Text = "未知";
        //                return;
        //            }
        //        }
        //    }
        //    string popMessage = "";
        //    Regex r = new Regex("您已通过登录审核");
        //    Match m = r.Match(returnContent);
        //    if (m.Success)
        //    {
        //        //setNotifyIcon1Status("已登录");
        //        //label_loginStatus.Text = "已登录";
        //        mainform.saveUserInfo();//save user name(password)
        //        //this.loginTime = DateTime.Now; //登录时间
        //        //if (checkBox_if_login.Checked)
        //        //{
        //        //    计费方式ToolStripMenuItem.Enabled = true;
        //        //    toolStripMenuItem4.Enabled = true;
        //        //}
        //        popMessage = "您已通过登录审核……";
        //        r = new Regex("费用不足，登录成功但不能访问校外");
        //        m = r.Match(returnContent);
        //        if (m.Success) //登录成功，但是没钱了
        //        {
        //            popMessage += "\n费用不足，登录成功但不能访问校外";
        //            //setNotifyIcon1Status("已登录，费用不足");
        //            //label_loginStatus.Text = "已登录，费用不足";
        //        }
        //        r = new Regex("用户名:UserID:");
        //        m = r.Match(returnContent);
        //        if (m.Success) //登录成功，也有钱，可以访问外网
        //        {
        //            string userName = NetCommon.getStringBetween(returnContent, "用户名:UserID:", "IP地址:IPAddress:");
        //            String ipAddress = NetCommon.getStringBetween(returnContent, "IP地址:IPAddress:", "网费查询");
        //            popMessage += "\n" + "用户名:" + userName;
        //            popMessage += "\n" + "IP地址:" + ipAddress;
        //        }
        //        if (!Settings.Default.isIEDisabled)
        //        {
        //            string url = mainform.checkBox_if_login.Checked ? Settings.Default.firstURL : Settings.Default.firstUrlIn;
        //            popMessage += "\n" + "单击这里打开" + url;
        //            mainform.balloonTipClickEnable = true;
        //            mainform.timer4.Enabled = true;
        //            mainform.urlType = URLTYPE_USER;
        //            if (Settings.Default.isAutoIE)
        //            {
        //                // System.Diagnostics.Process.Start(url);
        //                mainform.openUrl(url);
        //            }

        //        }

        //        if (mainform.定时退出帐户ToolStripMenuItem.Checked) //启动定时任务
        //        {
        //            popMessage += "\n已启动定时任务，您的帐户将会在";
        //            if (Settings.Default.isAutoQuitBytime)
        //            {
        //                mainform.timer1.Interval = 1000 * 60 * Convert.ToInt32(Settings.Default.autoQuitTime);
        //                //timer1.Interval = 1000 * 60 * 9999; //test max
        //                mainform.timer1.Enabled = true;
        //                popMessage += "计时达到" + Settings.Default.autoQuitTime + "分钟";
        //            }
        //            if (Settings.Default.isAutoQuitByflow && mainform.checkBox_if_login.Checked)//登陆外网的时候才有流量产生，方可启动流量监控
        //            {
        //                mainform.timer2.Enabled = true;
        //                if (Settings.Default.isAutoQuitBytime) popMessage += "或";
        //                popMessage += "流量达到" + Settings.Default.autoQuitFlow + "M ";
        //            }
        //            if (Settings.Default.isAutoQuitByMoney && mainform.checkBox_if_login.Checked)//登陆外网的时候才有费用产生，方可启动费用监控
        //            {
        //                if (Settings.Default.isAutoQuitBytime || Settings.Default.isAutoQuitByflow) popMessage += "或";
        //                mainform.timer_money.Enabled = true;
        //                popMessage += "费用达到" + Settings.Default.autoQuitMoney + "元";
        //            }
        //            popMessage += "后自动退出\n当前系统时间是：" + DateTime.Now.ToString();// +"\n为了保证退出帐户，请不要勾选自动重登";
        //            if (Settings.Default.isAutoQuitBytime && !Settings.Default.isAutoQuitByflow && !Settings.Default.isAutoQuitByMoney)
        //            {
        //                DateTime timeToQuit = DateTime.Now.AddMinutes(Convert.ToInt32(Settings.Default.autoQuitTime));
        //                popMessage += "\n预期退出时间是：" + timeToQuit.ToString();
        //            }
        //            //setNotifyIcon1Status("已登录，定时已启动");
        //            //label_loginStatus.Text = "已登录，定时已启动";
        //        }
        //        mainform.notifyIcon1.ShowBalloonTip(1000, "登录成功 ", popMessage, ToolTipIcon.Info);
        //        Log.WriteLine(mainform.txt_userName.Text.Trim(), popMessage);
        //        mainform.isLogin();//显示登录状态
        //        return;
        //    }
        //    r = new Regex("本机已经登录");
        //    m = r.Match(returnContent);
        //    if (m.Success)
        //    {
        //        if (mainform.checkBox_forceLogin.Checked)
        //        {
        //            mainform.logoutAndLogin(sender, e);
        //        }
        //        else
        //        {
        //            //setNotifyIcon1Status("已登录");
        //            //label_loginStatus.Text = "已登录";
        //            mainform.notifyIcon1.ShowBalloonTip(2000, "登录失败 ", "本机已经登录……\n请先退出登录", ToolTipIcon.Info);
        //            Log.WriteLine(mainform.txt_userName.Text.Trim(), "本机已经登录……\n请先退出登录");
        //        }
        //        return;
        //    }
        //    r = new Regex("账号已在其他计算机上登录");
        //    m = r.Match(returnContent);
        //    if (m.Success)
        //    {
        //        if (mainform.checkBox_forceLogin.Checked)
        //        {
        //            mainform.toolStripMenuItem2_Click(sender, e);//从其他地方退出
        //            mainform.logoutAndLogin(sender, e);//退出本地帐户，然后登录当前用户
        //        }
        //        else
        //        {

        //            mainform.notifyIcon1.ShowBalloonTip(2000, "登录失败 ", "账号已在其他计算机上登录，请先退出该账号", ToolTipIcon.Info);
        //            Log.WriteLine(mainform.txt_userName.Text.Trim(), "账号已在其他计算机上登录，请先退出该账号");
        //        }
        //        mainform.saveUserInfo();//save user name(password)
        //        return;
        //    }
        //    r = new Regex("密码错误");
        //    m = r.Match(returnContent);
        //    if (m.Success)
        //    {
        //        mainform.notifyIcon1.ShowBalloonTip(2000, "登录失败 ", "无法通过登录审核\n密码错误……\n请确认用户名和密码是否正确", ToolTipIcon.Info);
        //        Log.WriteLine(mainform.txt_userName.Text.Trim(), "无法通过登录审核\n密码错误……\n请确认用户名和密码是否正确");
        //        mainform.setNotifyIcon1Status("未登录");
        //        mainform.label_loginStatus.Text = "未登录";
        //        return;
        //    }
        //    r = new Regex("本机不是校内IP");
        //    m = r.Match(returnContent);
        //    if (m.Success)
        //    {
        //        mainform.notifyIcon1.ShowBalloonTip(2000, "登录失败 ", "无法通过登录审核\n本机不是校内IP……", ToolTipIcon.Info);
        //        Log.WriteLine(mainform.txt_userName.Text.Trim(), "无法通过登录审核\n本机不是校内IP……");
        //        mainform.setNotifyIcon1Status("未登录");
        //        mainform.label_loginStatus.Text = "未登录";
        //        return;
        //    }

        //}
    }
}
